from django.db import models
from ckeditor.fields import RichTextField
from django.shortcuts import reverse
# Create your models here.
from user.models import CustomUser

class Category(models.Model):
    title = models.CharField(verbose_name="分类名",max_length=100,unique=True)
    parent = models.ForeignKey(verbose_name="父级分类",to="Category",on_delete=models.CASCADE,blank=True,null=True)

    def children(self):
        return Category.objects.filter(parent=self)

    def __str__(self):
        return self.title


class Tag(models.Model):
    title = models.CharField(verbose_name="标签名",max_length=100,unique=True)

    def __str__(self):
        return self.title

class Files(models.Model):
    title = models.CharField(verbose_name="文件名",max_length=100)
    content = RichTextField(verbose_name="文件", blank=True, null=True)
    create_time = models.DateTimeField(verbose_name="发布时间",auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)

    author = models.ForeignKey("user.CustomUser", on_delete=models.CASCADE)
    categorys = models.ManyToManyField(verbose_name="所属分类", to=Category)
    tags = models.ManyToManyField(verbose_name="所有标签", to=Tag)

    download_url = models.URLField(verbose_name="下载地址", blank=True, null=True)
    state = models.CharField(verbose_name="审核状态", max_length=10, choices=(
        ('success', '已通过'),
        ('fail', '已驳回'),
        ('undo', '未处理')
    ), default='undo')

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('main:index')

    def tags_str(self):
        return ', '.join(t.title for t in self.tags.all())


class Comment(models.Model):
    # 修复：添加 'to' 参数，指定关联的 Files 模型
    file = models.ForeignKey(
        "Files",  # 或者使用 Files（如果已经在上面定义了）
        verbose_name='文件',
        on_delete=models.CASCADE,
        related_name='comments'
    )

    # 使用字符串引用 user.CustomUser
    user = models.ForeignKey(
        "user.CustomUser",
        verbose_name='用户',
        on_delete=models.CASCADE
    )

    content = models.TextField(verbose_name="评论内容")
    created_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_time']

    def __str__(self):
        return f"{self.user.username} - {self.file.title}"

